package com.zbkj.service.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Lists;
import com.zbkj.dal.base.enums.OrderOperateRecordTypeEnum;
import com.zbkj.dal.entity.order.OrderOperateRecord;
import com.zbkj.dal.pojo.response.OrderOperateRecordResponse;
import com.zbkj.dal.dao.OrderOperateRecordMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zbkj.service.service.OrderOperateRecordService;
import com.zbkj.service.service.SystemAdminService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jhui
 * @since 2023-11-06
 */
@Service
public class OrderOperateRecordServiceImpl extends ServiceImpl<OrderOperateRecordMapper, OrderOperateRecord> implements OrderOperateRecordService {

    @Autowired
    private SystemAdminService adminService;

    @Override
    public List<OrderOperateRecordResponse> listOrderOperateRecordsByOrderNo(String orderNo) {
        List<OrderOperateRecordResponse> recordResponses = Lists.newArrayList();
        LambdaQueryWrapper<OrderOperateRecord> queryWrapper = Wrappers.lambdaQuery(OrderOperateRecord.class);
        queryWrapper.eq(OrderOperateRecord::getOrderNo, orderNo);
        List<OrderOperateRecord> list = list(queryWrapper);

        for (OrderOperateRecord orderOperateRecord : list) {
            OrderOperateRecordResponse orderOperateRecordResponse = new OrderOperateRecordResponse();
            BeanUtils.copyProperties(orderOperateRecord, orderOperateRecordResponse);

            orderOperateRecordResponse.setStatusName(OrderOperateRecordTypeEnum.toName(orderOperateRecordResponse.getStatus()));
            recordResponses.add(orderOperateRecordResponse);
        }

        List<Integer> operatorIds = list.stream().filter(p -> p.getOperatorId() != null).map(m -> m.getOperatorId()).distinct().collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(operatorIds)) {
            Map<Integer, String> nameMapByIdList = adminService.getNameMapByIdList(operatorIds);
            for (OrderOperateRecordResponse dto : recordResponses) {
                if (dto.getOperatorId() != null) {
                    dto.setOperatorName(nameMapByIdList.get(dto.getOperatorId()));
                }
            }
        }

        return recordResponses;
    }
}
